import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;

public class SnakeHead extends GameObj {
    private String direction = "right";

    public String getDirection() {
        return direction;
    }

    public void setDirection(String direction) {
        this.direction = direction;
    }

    public SnakeHead(int x, int y, Image img, GameFrame frame) {
        super(x, y, img, frame);
        this.frame.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                changDirection(e);
            }
        });
    }

    //键盘控制蛇的方向
    public void changDirection(KeyEvent keyEvent) {
            switch (keyEvent.getKeyCode()) {
                case KeyEvent.VK_W:
                    direction = "up";
                    img = GameUtils.upImg;
                    break;
                case KeyEvent.VK_S:
                    direction = "down";
                    img = GameUtils.downImg;
                    break;
                case KeyEvent.VK_D:
                    direction = "right";
                    img = GameUtils.rightImg;
                    break;
                case KeyEvent.VK_A:
                    direction = "left";
                    img = GameUtils.leftImg;
                    break;
            }
        }

        public void move () {
                ArrayList<SnakeBody> snakeBodies = this.frame.snakeBodies;
                for (int i = snakeBodies.size() - 1; i >= 0; i--) {
                    if (i == 0) {
                        snakeBodies.get(i).x = this.x;
                        snakeBodies.get(i).y = this.y;
                    } else {
                        snakeBodies.get(i).x = snakeBodies.get(i - 1).x;
                        snakeBodies.get(i).y = snakeBodies.get(i - 1).y;
                    }
                }
            switch (direction) {
                case "right":
                    x += frame.step;
                    x = x > frame.frameWidth - frame.step ? 0 : x;
                    break;
                case "left":
                    x += frame.step;
                    x = x < 0 ? frame.frameWidth - frame.step : x;
                    break;
                case "up":
                    y += frame.step;
                    y = y < 0 ? frame.frameWidth - frame.step : y;
                    break;
                case "down":
                    y += frame.step;
                    y = y > frame.frameWidth - frame.step ? 0 : y;
                    break;
            }
        }
        @Override
        public void paintSelf (Graphics graphics){
            super.paintSelf(graphics);
            move();
        }
    }
